import React from "react";
import {get} from "../network/request"
import workBackImg from '../assets/img/workBack.png'
import work001 from '../assets/img/work001.png'
import work002 from '../assets/img/work002.png'
import work003 from '../assets/img/work003.png'
import work004 from '../assets/img/work004.png'
import work005 from '../assets/img/work005.png'
import work006 from '../assets/img/work006.png'
import work007 from '../assets/img/work007.png'
import work008 from '../assets/img/work008.png'
import '../style/common.css'

import {postFormData } from "../network/request"

class WorkType extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            workTypeList : [
                
            ]
        }
    }

    componentDidMount(){
        this.scrollToTop()
        this.getJobTypeList()
    }

    getJobTypeList(){
        get("/jobList")
            .then(response => {
               if (response && response["success"] === true && response.data) {
                    let workTypeList = response.data.map((item, index) => {
                        // 这里假设每个item都有name和img属性
                        item.id = index; // 使用index作为id
                        switch (index) {
                            case 0:
                                item.img = work001;
                                break;
                            case 1:
                                item.img = work002;
                                break;
                            case 2:
                                item.img = work003;
                                break;
                            case 3:
                                item.img = work004;
                                break;
                            case 4:
                                item.img = work005;
                                break;
                            case 5:
                                item.img = work006;
                                break;
                            case 6:
                                item.img = work007;
                                break;
                            case 7:
                                item.img = work008;
                                break;
                            default:
                                item.img = work001; // 默认图片
                        }
                        item.select = false; // 初始化选择状态
                        return item;
                        
                    });
                    this.setState({workTypeList: workTypeList});    

                }
            })
        .catch(error => {
                console.error("数据获取失败:", error);
        }); 
    }


    scrollToTop(){
        window.scrollTo({
          top: 0,
          behavior: 'smooth',
        });
    }

    selectWorkType = (id)=>{
        let workTypeList = this.state.workTypeList

        let selectCount = 0
        let selectIdList = []

        workTypeList.forEach((item) => {
            if(item.select){
                selectCount++
                selectIdList.push(item.id)
            }
        })

        if(selectCount >= 5 && !selectIdList.includes(id)){
            return
        }

        workTypeList[id].select = !workTypeList[id].select
        this.setState({workTypeList : workTypeList})
    }


    submitWorkType(){
        if (this.state.workTypeList.filter(item => item.select).length < 3) {
            alert("Please select at least 3 job categories.");
            return;
        }

        // 获取用户UserId
        let userInfo = localStorage.getItem("initUser")
        let userJson = JSON.parse(userInfo);
        var userId = userJson["user_id"];

        const formData = new FormData();
        formData.append("userId", userId);
        formData.append("selectJobIds", this.state.workTypeList.filter(item => item.select).map(item => item.job_id).join(','));
        postFormData("/selectJob", formData)
            .then(response => {
                if (response && response["success"] === true) {
                    // 更新本地存储的用户信息
                    userJson["job_ids"] = this.state.workTypeList.filter(item => item.select).map(item => item.job_id).join(',');
                    localStorage.setItem("initUser", JSON.stringify(userJson));

                    // 调用父组件的回调函数
                    this.props.onClick()
                }
            })
            .catch(error => {
                console.error("数据提交失败:", error);
            });
    }


    render(){
        return (
            <div className="WorkTypeV">
                <div className="WorkTypeTitleV">
                    <img src={workBackImg} className="WorkTypeImgV" onClick={this.props.onBackClick}></img>
                    <p className="WorkTypeTitleL">What job you want?</p>1
                    <div className="WorkTypeEmptyV"></div>
                </div>
                
                <div className="WorkTypeContentV">
                    <p className="WorkTypeContentL">Choose 3-5 job categories and we’ll optimize the job vacancy for you.</p>
                </div>

                <div className="WorkTypeSelectV">
                    {this.state.workTypeList.map((item, index) => (
                        <div className="WorkTypeSelectItemV" key={index} style={{borderColor: item.select ? '#2972FE' : '#394452'}} onClick={() => this.selectWorkType(index)}>
                            <img src={item.img} className="WorkTypeSelectImgV"></img>
                            <p className="WorkTypeSelectTitleL">{item.name}</p>
                        </div>
                    ))}
                </div>
                <div className="WorkTypeBottomV"></div>

                <div className="WorkTypeBtnV" onClick={this.submitWorkType.bind(this)}>
                    <p className="WorkTypeBtnL">Next</p>
                </div>
            </div>
        )
    }
}

export default WorkType